import pygame
import os
import random
import time
import START
class Pokemon:
    """宝可梦类，包含属性和技能"""
    def __init__(self, name, hp, image_path):
        self.name = name
        self.max_hp = hp
        self.current_hp = hp
        self.image = pygame.image.load(os.path.join("image", image_path))
        self.skills = [
            {"name": "撞击", "damage": 10, "effect": None},
            {"name": "寄生种子", "damage": 5, "effect": "leech"},
            {"name": "变硬", "damage": 0, "effect": "defense_up"},
            {"name": "百万吨拳击", "damage": 15, "effect": None}
        ]
    
    def use_skill(self, skill_index, target, battle_info):
        """使用技能攻击目标"""
        skill = self.skills[skill_index]
        battle_info.add_message(f"{self.name} 使用了 {skill['name']}!")
        
        if skill["effect"] == "leech":
            damage = skill["damage"]
            heal = damage / 2
            target.take_damage(damage, battle_info)
            self.heal(heal)
            battle_info.add_message(f"{self.name} 吸收了 {heal} HP!")
            pygame.display.update()  # 立即更新显示
        elif skill["effect"] == "defense_up":
            battle_info.add_message(f"{self.name} 防御提升了!")
            pygame.display.update()  # 立即更新显示
        else:
            target.take_damage(skill["damage"], battle_info)
            pygame.display.update()  # 立即更新显示
    
    def take_damage(self, amount, battle_info):
        """受到伤害"""
        self.current_hp -= amount
        battle_info.add_message(f"{self.name} 受到了 {amount} 点伤害!")
        if self.current_hp <= 0:
            battle_info.add_message(f"{self.name} 倒下了!")
            self.current_hp = 0
    
    def heal(self, amount):
        """恢复HP"""
        self.current_hp = min(self.max_hp, self.current_hp + amount)

# 生成窗口
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("POKEMON")

class Button:
    def __init__(self, x, y, width, height, color, text=''):
        # 创建更大的背景区域
        self.background = pygame.Surface((width + 20, height + 10), pygame.SRCALPHA)
        self.background.fill((255, 255, 0, 128))  # 黄色背景
        self.background_rect = self.background.get_rect(center=(x + width//2, y + height//2))
        
        # 使用背景区域作为按钮区域
        self.rect = self.background_rect
        self.color = color
        self.text = text
        self.font = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 32)
        self.text_surface = self.font.render(text, True, (0, 0, 20))

    def draw(self, surface):
        # 绘制按钮背景
        surface.blit(self.background, self.background_rect)
        # 绘制文本
        text_rect = self.text_surface.get_rect(center=self.background_rect.center)
        surface.blit(self.text_surface, text_rect)

    def is_clicked(self, pos):
        # 使用背景区域进行点击检测
        return self.background_rect.collidepoint(pos)

# 加载文字
font = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 64)
font2 = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 20)

# 加载音效
pygame.mixer.init()
sound_select = pygame.mixer.Sound(os.path.join("sound", "select07.mp3"))
sound_attack = pygame.mixer.Sound(os.path.join("sound", "middle_punch1.mp3"))
sound_seed = pygame.mixer.Sound(os.path.join("sound", "breaking_branchs2.mp3")) 
sound_defense = pygame.mixer.Sound(os.path.join("sound", "damage7.mp3"))
sound_punch = pygame.mixer.Sound(os.path.join("sound", "middle_punch1.mp3"))
backmusic = pygame.mixer.Sound(os.path.join("sound", "backsound.mp3"))

# 设置音量
sound_select.set_volume(0.5)
sound_attack.set_volume(0.7)
sound_seed.set_volume(0.7)
sound_defense.set_volume(0.7)
sound_punch.set_volume(0.7)
backmusic.set_volume(1.0)

def start_game():
    # 开始游戏
    #backmusic.play(-1)  # 背景音乐循环播放
    START = False
    
    # 宝可梦图片和音效列表
    pokemon_data = [
        {
            "image": pygame.transform.scale(pygame.image.load(os.path.join("image", "2.png")), (200, 200)),
            "sound": pygame.mixer.Sound(os.path.join("sound", "tung_tung_tung_tung_sahur.mp3"))  # 修改文件名，去掉空格
        },
        {
            "image": pygame.transform.scale(pygame.image.load(os.path.join("image", "1.png")), (200, 200)),
            "sound": pygame.mixer.Sound(os.path.join("sound", "trailer_tralala.mp3"))  # 修改文件名，去掉空格
        }
    ]
    current_img_index = 0
    pokemon_img = pokemon_data[current_img_index]["image"]
    pokemon_rect = pokemon_img.get_rect(topleft=(300, 150))
    
    # 显示文字
    text = font.render("POKEMON(半成品)", True, (0, 0, 0))
    text2 = font2.render("小组成员：文皓玉，罗祖梁，耶尔森，王洪铭" , True, (0, 0, 0))

    # 创建按钮
    button1 = Button(350, 400, 100, 50, (0, 128, 0), '开始游戏')
    button2 = Button(350, 500, 100, 50, (0, 128, 0), '读档')

    # 主循环
    while not START:
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            if event.type == pygame.MOUSEBUTTONDOWN:  # 鼠标按下事件
                if button1.is_clicked(event.pos):  # 检查按钮是否被点击
                    sound_select.play()  # 播放选择音效
                    print("按钮被点击！")
                    START = True
                elif pokemon_rect.collidepoint(event.pos):  # 检查图片是否被点击
                    current_img_index = (current_img_index + 1) % len(pokemon_data)
                    pokemon_img = pokemon_data[current_img_index]["image"]
                    pokemon_data[current_img_index]["sound"].play()  # 播放对应音效
                    print(f"切换宝可梦图片: {current_img_index + 1}")

        # 绘制屏幕
        screen.fill((255, 255, 255))
        screen.blit(text, (text.get_rect(center=(400, 50))))
        screen.blit(text2, (text2.get_rect(center=(400, 100))))
        # 绘制宝可梦图片
        screen.blit(pokemon_img, pokemon_rect)
        button1.draw(screen)  # 绘制按钮
        button2.draw(screen)  # 绘制按钮
        pygame.display.update()

    return START  # 返回状态以决定是否进入游戏

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()


    def update(self, keys):
        if keys[pygame.K_LEFT]:
            self.rect.x -= 5
        if keys[pygame.K_RIGHT]:
            self.rect.x += 5
        if keys[pygame.K_UP]:
            self.rect.y -= 5
        if keys[pygame.K_DOWN]:
            self.rect.y += 5

class BattleScene:
    """战斗场景类"""
    def __init__(self, player_pokemon, enemy_pokemon):
        self.player = player_pokemon
        self.enemy = enemy_pokemon
        self.skill_buttons = [
            Button(100, 450, 120, 50, (100, 200, 100), self.player.skills[0]["name"]),
            Button(250, 450, 120, 50, (100, 200, 100), self.player.skills[1]["name"]),
            Button(400, 450, 120, 50, (100, 200, 100), self.player.skills[2]["name"]),
            Button(550, 450, 120, 50, (100, 200, 100), self.player.skills[3]["name"])
        ]
        self.font = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 24)
        self.player_turn = True
        self.action_cooldown = 0

    def draw(self, surface):
        """绘制战斗界面"""
        # 绘制背景
        surface.fill((240, 240, 240))
        
        # 重新布局界面元素
        # 1. 保持比例调整图片大小
        def resize_image(image, max_size=300):  # 增大图片尺寸
            """保持宽高比缩放图片"""
            width = image.get_width()
            height = image.get_height()
            ratio = min(max_size/width, max_size/height)
            return pygame.transform.smoothscale(image, (int(width*ratio), int(height*ratio)))
        
        player_img = resize_image(self.player.image)
        enemy_img = resize_image(self.enemy.image)
        
        # 2. 信息区域 - 左上角 (20,20)-(400,150)
        info_bg = pygame.Rect(20, 20, 380, 130)
        pygame.draw.rect(surface, (200, 200, 200), info_bg)
        
        # 3. 图片区域 - 调整位置和大小
        surface.blit(enemy_img, (450, 150))  # 敌方图片位置调整
        self.draw_health_bar(surface, 450, 130, self.enemy)
        
        surface.blit(player_img, (100, 300))  # 玩家图片位置调整
        self.draw_health_bar(surface, 100, 280, self.player)
        
        # 4. 操作区域 - 右下角 (450,450)-(750,550)
        button_start_x = 500
        button_y = 470
        for i, button in enumerate(self.skill_buttons):
            button.rect.x = button_start_x + (i%2)*150
            button.rect.y = button_y + (i//2)*60
            button.draw(surface)
        pygame.draw.rect(surface, (200, 200, 200), info_bg)
    
    def draw_health_bar(self, surface, x, y, pokemon):
        """绘制血条"""
        bar_width = 200
        bar_height = 20
        fill = (pokemon.current_hp / pokemon.max_hp) * bar_width
        
        # 绘制血条背景
        pygame.draw.rect(surface, (200, 200, 200), (x, y, bar_width, bar_height))
        # 绘制当前血量
        pygame.draw.rect(surface, (0, 200, 0), (x, y, fill, bar_height))
        # 绘制血条文字
        text = self.font.render(f"{pokemon.current_hp}/{pokemon.max_hp}", True, (0, 0, 0))
        surface.blit(text, (x + bar_width + 10, y))
    
    def handle_click(self, pos, battle_info):
        """处理按钮点击"""
        if not self.player_turn:
            return None
            
        for i, button in enumerate(self.skill_buttons):
            if button.is_clicked(pos):
                # 立即显示战斗信息
                skill_name = self.player.skills[i]["name"]
                print(f"{self.player.name} 使用了 {skill_name}!")
                battle_info.add_message(f"{self.player.name} 使用了 {skill_name}!")
                
                # 执行技能效果
                self.player.use_skill(i, self.enemy, battle_info)
                
                self.player_turn = False  # 结束玩家回合
                
                skill_name = self.player.skills[i]["name"]
                battle_info.add_message(f"{self.player.name} 使用了 {skill_name}!")
                
                # 播放玩家技能音效
                if skill_name == "撞击":
                    sound_attack.play()
                elif skill_name == "寄生种子":
                    sound_seed.play()
                elif skill_name == "变硬":
                    sound_defense.play()
                elif skill_name == "百万吨拳击":
                    sound_punch.play()
                
                # 玩家技能效果
                self.player.use_skill(i, self.enemy, battle_info)
                
                # 返回玩家行动结果
                return {
                    "damage_dealt": self.player.skills[i]["damage"],
                    "player_action": True,
                    "skill_index": i
                }
        return None

    def enemy_turn(self, battle_info):
        """敌方行动回合"""
        if self.enemy.current_hp <= 0:
            return None
            
        enemy_skill = random.randint(0, 3)
        skill_name = self.enemy.skills[enemy_skill]["name"]
        battle_info.add_message(f"{self.enemy.name} 使用了 {skill_name}!")
        
        # 播放敌方技能音效
        if skill_name == "撞击":
            sound_attack.play()
        elif skill_name == "寄生种子":
            sound_seed.play()
        elif skill_name == "变硬":
            sound_defense.play()
        elif skill_name == "百万吨拳击":
            sound_punch.play()
        
        # 敌方技能效果
        self.enemy.use_skill(enemy_skill, self.player, battle_info)

        # 返回敌方行动结果
        return {
            "damage_taken": self.enemy.skills[enemy_skill]["damage"],
            "enemy_action": True,
            "skill_index": enemy_skill
        }
        self.player = player_pokemon
        self.enemy = enemy_pokemon
        self.skill_buttons = [
            Button(100, 450, 120, 50, (100, 200, 100), self.player.skills[0]["name"]),
            Button(250, 450, 120, 50, (100, 200, 100), self.player.skills[1]["name"]),
            Button(400, 450, 120, 50, (100, 200, 100), self.player.skills[2]["name"]),
            Button(550, 450, 120, 50, (100, 200, 100), self.player.skills[3]["name"])
        ]
        self.font = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 24)
        self.player_turn = True
        self.action_cooldown = 0

    def handle_click(self, pos, battle_info):
        """处理按钮点击"""
        if not self.player_turn:
            return None
            
        for i, button in enumerate(self.skill_buttons):
            if button.is_clicked(pos):
                # 锁定按钮直到回合结束
                self.button_locked = True
                
                skill_name = self.player.skills[i]["name"]
                battle_info.add_message(f"玩家选择了技能: {skill_name}")
                
                # 播放玩家技能音效
                if skill_name == "撞击":
                    sound_attack.play()
                elif skill_name == "寄生种子":
                    sound_seed.play()
                elif skill_name == "变硬":
                    sound_defense.play()
                elif skill_name == "百万吨拳击":
                    sound_punch.play()
                
                damage = self.player.skills[i]["damage"]
                self.player.use_skill(i, self.enemy, battle_info)
                
                # 返回玩家行动结果
                return {
                    "damage_dealt": damage,
                    "player_action": True,
                    "skill_index": i
                }
        return None

    def enemy_turn(self, battle_info):
        """敌方行动回合"""
        if self.enemy.current_hp <= 0:
            return None
            
        enemy_skill = random.randint(0, 3)
        skill_name = self.enemy.skills[enemy_skill]["name"]
        battle_info.add_message(f"敌方使用了 {skill_name}!")
        
        # 播放敌方技能音效
        if skill_name == "撞击":
            sound_attack.play()
        elif skill_name == "寄生种子":
            sound_seed.play()
        elif skill_name == "变硬":
            sound_defense.play()
        elif skill_name == "百万吨拳击":
            sound_punch.play()
        
        damage = self.enemy.skills[enemy_skill]["damage"]
        self.enemy.use_skill(enemy_skill, self.player, battle_info)
        
        # 返回敌方行动结果
        return {
            "damage_taken": damage,
            "enemy_action": True,
            "skill_index": enemy_skill
        }

class BattleInfo:
    """战斗信息显示类"""
    def __init__(self):
        self.messages = []
        self.font = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 18)  # 减小字体大小
        self.max_lines = 8  # 增加最大行数
        self.original_image = None  # 保存原始图像用于抖动恢复
    
    def add_message(self, message):
        """添加战斗消息并立即更新显示"""
        print(message)  # 确保终端同步输出
        self.messages.append(message)
        if len(self.messages) > self.max_lines:
            self.messages.pop(0)
        # 立即渲染并更新显示
        self.draw(pygame.display.get_surface())
        pygame.display.flip()
    
    def draw(self, surface):
        """绘制战斗信息"""
        # 清除信息区域背景
        info_bg = pygame.Rect(15, 15, 400, 200)  # 扩大边框
        pygame.draw.rect(surface, (200, 200, 200), info_bg)
        
        # 在信息区域内绘制消息
        info_start_x = 25
        info_start_y = 20
        line_height = 22  # 调整行间距
        
        for i, msg in enumerate(self.messages[-self.max_lines:]):
            text = self.font.render(msg, True, (0, 0, 0))
            surface.blit(text, (info_start_x, info_start_y + i * line_height))
            
            # 添加分割线
            if i < len(self.messages)-1:
                pygame.draw.line(surface, (180,180,180), 
                               (info_start_x, info_start_y + i * line_height + 20),
                               (info_start_x + 350, info_start_y + i * line_height + 20), 1)

def start_game2():
    backmusic.play(-1)  # 背景音乐循环播放
    # 创建宝可梦实例
    pikachu = Pokemon("trailer tralala", 100, "1.png")
    charizard = Pokemon("tung tung tung sahur", 150, "2.png")
    
    # 初始化战斗信息
    battle_info = BattleInfo()
    battle_info.add_message("游戏开始!")
    
    # 战斗统计
    battle_stats = {
        "damage_dealt": 0,
        "damage_taken": 0
    }

    in_battle = True  # 直接进入战斗
    battle_scene = BattleScene(pikachu, charizard)
    battle_info.add_message("野生喷火龙出现了!")

    clock = pygame.time.Clock()
    shake_effect = False
    shake_offset = 0
    shake_duration = 0

    while True:
        # 冷却计时
        if battle_scene.action_cooldown > 0:
            battle_scene.action_cooldown -= 1
            
        # 处理抖动效果
        if shake_effect:
            shake_duration -= 1
            shake_offset = random.randint(-5, 5)
            if shake_duration <= 0:
                shake_effect = False
                shake_offset = 0

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            if event.type == pygame.MOUSEBUTTONDOWN and in_battle:
                action_result = battle_scene.handle_click(event.pos, battle_info)
                if action_result and action_result.get("player_action"):
                    # 玩家行动后触发敌方行动
                    pygame.display.update()
                    time.sleep(1.0)  # 玩家行动后延迟
                    
                    # 立即更新界面显示玩家行动结果
                    pygame.display.update()
                    
                    # 短暂延迟后执行敌方行动(0.8秒)
                    time.sleep(0.8)
                    
                    if battle_scene.enemy.current_hp > 0:
                        # 立即显示敌方行动信息
                        enemy_result = battle_scene.enemy_turn(battle_info)
                        pygame.display.update()
                        
                        if enemy_result:
                            # 敌方行动抖动效果
                            shake_effect = True
                            shake_duration = 10
                            # 短暂延迟后继续(0.8秒)
                            time.sleep(0.8)
                    
                    # 更新战斗统计
                    battle_stats["damage_dealt"] += action_result.get("damage_dealt", 0)
                    if enemy_result:
                        battle_stats["damage_taken"] += enemy_result.get("damage_taken", 0)
                    
                    # 检查战斗结果
                    if battle_scene.player.current_hp <= 0:
                        battle_info.add_message("战斗失败!")
                        in_battle = False
                        show_result_screen(screen, battle_stats)
                        pygame.display.update()
                        time.sleep(3)
                        # 重置战斗
                        battle_scene.player.current_hp = battle_scene.player.max_hp
                        battle_scene.enemy.current_hp = battle_scene.enemy.max_hp
                        battle_stats = {"damage_dealt": 0, "damage_taken": 0}
                        in_battle = True
                        battle_info.add_message("新的战斗开始!")
                        battle_scene.player_turn = True
                    elif battle_scene.enemy.current_hp <= 0:
                        battle_info.add_message("战斗胜利!")
                        in_battle = False
                        show_result_screen(screen, battle_stats)
                        pygame.display.update()
                        time.sleep(3)
                        # 重置战斗
                        battle_scene.player.current_hp = battle_scene.player.max_hp
                        battle_scene.enemy.current_hp = battle_scene.enemy.max_hp
                        battle_stats = {"damage_dealt": 0, "damage_taken": 0}
                        in_battle = True
                        battle_info.add_message("新的战斗开始!")
                        battle_scene.player_turn = True

        # 绘制战斗场景
        screen.fill((0, 0, 0))
        
        # 应用抖动效果并确保复原
        if shake_effect:
            if not hasattr(battle_scene.player, 'original_image'):
                battle_scene.player.original_image = battle_scene.player.image.copy()
            battle_scene.player.image = pygame.transform.rotate(battle_scene.player.original_image, shake_offset)
        elif hasattr(battle_scene.player, 'original_image'):
            battle_scene.player.image = battle_scene.player.original_image
        
        battle_scene.draw(screen)
        battle_info.draw(screen)
        
        pygame.display.update()
        clock.tick(60)

def show_result_screen(surface, stats):
    """显示结算页面"""
    surface.fill((80, 80, 150))  # 更亮的背景色
    font_large = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 48)
    font_normal = pygame.font.Font(os.path.join("font", "IPix中文像素字体.ttf"), 36)
    
    title = font_large.render("战斗结算", True, (255, 255, 0))  # 黄色标题
    damage_dealt = font_normal.render(f"总造成伤害: {stats['damage_dealt']}", True, (255, 255, 255))
    damage_taken = font_normal.render(f"总受到伤害: {stats['damage_taken']}", True, (255, 255, 255))
    
    # 添加装饰性边框
    pygame.draw.rect(surface, (255, 215, 0), (200, 100, 400, 300), 5)
    
    surface.blit(title, (400 - title.get_width()//2, 120))
    surface.blit(damage_dealt, (400 - damage_dealt.get_width()//2, 220))
    surface.blit(damage_taken, (400 - damage_taken.get_width()//2, 280))


start_game()  # 只有当游戏被开始时才会进入游戏2
start_game2()
